<template>
    <div class="box" @mousemove="showZoom($event)" @mouseleave="hideZoom">
        <img :src="imageUrl" alt="">
        <div class="zhezhao" ref="zoomMask"></div>
        <div class="big" ref="zoomContainer">
            <img :src="imageUrl" alt="">
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import cs from '../assets/images/D4F7E8C70F75639BF87F6FF720B8F548.png'
const imageUrl = ref(cs);
const zoomMask = ref<HTMLElement | null>(null);
const zoomContainer = ref<HTMLElement | null>(null);

const showZoom = (e: any) => {
    if (zoomMask.value && zoomContainer.value) {
        zoomMask.value.style.display = 'block';
        zoomContainer.value.style.display = 'block';

        const boxRect:any = e.currentTarget.getBoundingClientRect();
        const mouseX = e.clientX - boxRect.left;
        const mouseY = e.clientY - boxRect.top;

        moveZoom(mouseX, mouseY);
    }
};

const hideZoom = () => {
    if (zoomMask.value && zoomContainer.value) {
        zoomMask.value.style.display = 'none';
        zoomContainer.value.style.display = 'none';
    }
};

const moveZoom = (mouseX: number, mouseY: number) => {
    if (zoomMask.value && zoomContainer.value) {
        const zoomMaskSize = 100; // 设置放大镜尺寸
        const zoomContainerSize = 500; // 设置放大容器尺寸

        const maskLeft = mouseX - zoomMaskSize / 2;
        const maskTop = mouseY - zoomMaskSize / 2;

        zoomMask.value.style.left = `${maskLeft}px`;
        zoomMask.value.style.top = `${maskTop}px`;

        const scale = zoomContainerSize / zoomMaskSize;
        zoomContainer.value.querySelector('img')!.style.left = `-${maskLeft * scale}px`;
        zoomContainer.value.querySelector('img')!.style.top = `-${maskTop * scale}px`;
    }
};
</script>

<style>
* {
    margin: 0;
    padding: 0;
}

.box {
    width: 360px;
    height: 360px;
    position: relative;
}

.box>img {
    width: 360px;
    height: 360px;
}

.big {
    position: absolute;
    top: 0;
    left: 380px;
    width: 360px;
    height: 360px;
    overflow: hidden;
    display: none;
}

.big img {
    position: absolute;
    top: 0;
    left: 0;
}

.zhezhao {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background-color: rgba(0, 0, 0, .3);
    cursor: move;
    display: none;
}
</style>
